package com.bilibili.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zuife
 * @description
 * 实现一个自旋锁，复习CAS思想
 * 自旋锁的好处：循环比较获取没有类似wait的阻塞
 * 通过CAS操作完成自旋锁，A线程先进来调用myLock方法自己持有锁5秒钟，B随后进来发现当前线程持有锁，所有只能通过自旋等待，直到A释放锁后B随后抢到。
 * @since 2024-05-03 08:49:42
 */
public class SpinLockDemo {
    AtomicReference atomicReference = new AtomicReference<>();
    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+" come in");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }
    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+" invoked unlock");
    }
    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            spinLockDemo.lock();
            // 暂停一会儿线程
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //解锁
            spinLockDemo.unlock();
        },"A").start();
        //暂停500毫秒，线程A先于B启动
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new Thread(()->{
            //加锁
            spinLockDemo.lock();
            //暂停一会儿线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //解锁
            spinLockDemo.unlock();
        },"B").start();
    }
}
